<?php

namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class CorsMiddleware implements MiddlewareInterface
{
    protected $cookieDomain;

    protected $header = [
        //'Access-Control-Allow-Origin' => '*', // *代表允许任何网址请求
        'Access-Control-Allow-Credentials' => 'true', // 设置是否允许发送 cookies
        'Access-Control-Max-Age' => 1800,
        'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS', // 允许请求的类型
        //'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With', // 设置允许自定义请求头的字段
        'Access-Control-Allow-Headers' => '*', // 支持头部带token字段
    ];

    public function __construct()
    {
        $this->cookieDomain = config('cookie.domain', '');
    }

    public function process(Request $request, callable $handler) : Response
    {
        // 如果是opitons请求则返回一个空的响应，否则继续向洋葱芯穿越，并得到一个响应
        $response = $request->method() == 'OPTIONS' ? response('') : $handler($request);

        $header = !empty($header) ? array_merge($this->header, $header) : $this->header;

        if (!isset($header['Access-Control-Allow-Origin'])) {
            $origin = $request->header('origin');

            if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) {
                $header['Access-Control-Allow-Origin'] = $origin;
            } else {
                $header['Access-Control-Allow-Origin'] = '*';
            }
        }

        // 给响应添加跨域相关的http头
//        $response->withHeaders([
//            'Access-Control-Allow-Credentials' => 'true',
//            'Access-Control-Allow-Origin' => $request->header('origin', '*'),
//            'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
//            'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
//        ]);
        $response->withHeaders($header);

        return $response;
    }
}
